//
//  HomeHeaderViewController.m
//  MMLOOK
//
//  Created by dllo on 15/9/4.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "HomeHeaderViewController.h"
#import "AsynConnect.h"
#import "HomeCollectionViewCell.h"
#import "HomeDeatViewController.h"
#import "MJRefresh.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"
#import "SaveTools.h"
#import "JudgeConnection.h"
#import "Alert.h"
#import "MBProgressHUD.h"

@interface HomeHeaderViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)UICollectionView *collection;
@property (nonatomic, retain)NSMutableArray *homeArray;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain) MBProgressHUD *mbProView;

@end

@implementation HomeHeaderViewController

- (void)dealloc
{
    [_mbProView release];
    [_url release];
    [_titleStr release];
    [_homeArray release];
    [_collection release];
    [_homedic release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.homedic = [NSMutableDictionary dictionary];
        self.homeArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.titleStr;
    self.url = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?gender=2&generation=1&limit=20&offset=0", [self.homedic objectForKey:@"target_id"]];
    
    [self creatCollection];
    [self readLocalData];
    [self Connection];
    self.view.backgroundColor = [UIColor whiteColor];
    [self conectXLSX];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
}

- (void)creatCollection
{
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.width * 328 / 720);
    layout.minimumInteritemSpacing = 15 * OffHeight;
    layout.sectionInset = UIEdgeInsetsMake(15 * OffHeight, 15 * OffWidth, 15 * OffHeight, 15 * OffWidth);
    
    self.collection = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:layout] autorelease];
    _collection.dataSource = self;
    _collection.delegate = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [_collection registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:@"home"];
    [self.view addSubview:_collection];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_homeArray.count == 0) {
        return 0;
    }
    return _homeArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"home" forIndexPath:indexPath];
    NSMutableDictionary *dic = [_homeArray objectAtIndex:indexPath.row];
    [cell sendDic:dic];
    
    return cell;
}

- (void)Connection
{
    [self createMbProView];
    
    [AsynConnect asynConnectWithUrlstr:_url parmater:nil block:^(NSData *data) {
        
        if (data) {
            
            BOOL saveResult = [SaveTools saveDataWithName:[_url hash] directory:NSLibraryDirectory data:data];// 有网络时 数据储存在本地
            NSLog(@"轮播页详情存储: %d", saveResult);
            
            [self.homeArray removeAllObjects];
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
            NSMutableArray *arr = [littleDic objectForKey:@"posts"];
            [self.homeArray addObjectsFromArray:arr];
            [_collection reloadData];
            
            [_mbProView hide:YES];
        }
    }];
}

- (void)readLocalData
{
    NSData *data = [SaveTools readDataWithName:[_url hash] directory:NSLibraryDirectory];
    if (data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *littleDic = [dic objectForKey:@"data"];
        NSMutableArray *arr = [littleDic objectForKey:@"posts"];
        [self.homeArray addObjectsFromArray:arr];
        [_collection reloadData];
    }
}

- (void)conectXLSX
{
    _collection.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [_homeArray removeAllObjects];
        [self readLocalData];
        [self Connection];// 处理数据
        [_collection reloadData];// 刷新数据
        [_collection.header endRefreshing];// 结束刷新
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (![JudgeConnection judgeConnection]) {
        Alert *alert = [[Alert alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 250) / 2, self.view.frame.size.height * 3 / 4, 250, 50) LabelText:@"当前无网络连接，请检查网络状态"];
        [self.view addSubview:alert];
        [alert release];
    } else {
        HomeDeatViewController *homedeta = [[[HomeDeatViewController alloc] init] autorelease];
        homedeta.dic = [_homeArray objectAtIndex:indexPath.item];
        [self.navigationController pushViewController:homedeta animated:YES];
    }
}

- (void)createMbProView
{
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    _mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    _mbProView.labelText = @"加载中. . .";
    [_mbProView show:YES];
    [self.view addSubview:_mbProView];
    [_mbProView hide:YES afterDelay:20];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
